package com.shop.listener;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.shop.entity.UserInfo;
@WebListener
public class OnLineListener implements 
ServletContextListener,HttpSessionListener,HttpSessionAttributeListener {

	 public void contextInitialized(ServletContextEvent sce){
		 //1.创建集合
		 Set<UserInfo> set = new HashSet<UserInfo>();
		//2.存储在application
		 ServletContext application = sce.getServletContext();
		 application.setAttribute("users",set);
	 }
	 //从集合中删除用户
	 public void sessionDestroyed(HttpSessionEvent se){
		 //1.获取session
		 HttpSession session = se.getSession();
		 //2.获取用户
		 UserInfo user =  (UserInfo) session.getAttribute("u");
		 //3.获取application
		 ServletContext application = session.getServletContext();
		 //4.获取集合
		 Set<UserInfo> set  =	 (Set<UserInfo>) application.getAttribute("users");
		 //5.移除用户对象
		 set.remove(user);
	 }
	 //登录成功添加用户到集合
	 @SuppressWarnings("unchecked")
	 public void attributeAdded(HttpSessionBindingEvent event){
		 //1.获取session
		 HttpSession session = event.getSession();
		 //2.获取用户
		 UserInfo user = (UserInfo)session.getAttribute("u");
		 //3.添加到set集合
		 ServletContext application = event.getSession().getServletContext();
		 Set<UserInfo>  set = (Set<UserInfo>) application.getAttribute("users");
		 set.add(user);
	 }
}
